package com.im.app.controller;

import com.im.app.authConfig.CurrentUser;
import com.im.app.authConfig.RequireLogin;
import com.im.app.manager.ChatLogManager;
import com.im.app.manager.ConversationManager;
import com.im.app.model.ChatLogs;
import com.im.app.model.Conversations;
import com.im.app.model.User;
import com.im.app.model.Welcome;
import com.im.app.service.ChatLogsService;
import com.im.app.service.ConversationsService;
import com.im.app.service.IUserService;
import com.im.app.service.WelcomeService;
import com.im.app.utils.Response;
import com.im.app.utils.ResponseResult;
import com.im.app.utils.StringUtils;
import org.jim.core.ImPacket;
import org.jim.core.packets.*;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;

import java.util.*;

/**
 * 聊天消息控制器
 */
@RestController
@RequestMapping(value = "/message")
public class IMMessageController extends BaseController{

    @Resource
    private ChatLogsService chatLogsService;
    @Resource
    private ConversationsService conversationsService;
    @Resource
    private WelcomeService welcomeService;
    @Resource
    private IUserService userService;


    /**
     * 获取历史查询消息记录
     * @param user
     * @param userId
     * @return
     */
    @RequireLogin
    @GetMapping(value ="/getHistory")
    public ResponseResult<Object> getHistory(@CurrentUser User user, String userId,String groupId, String msgId){
        Long createTime = new Date().getTime();
        if(StringUtils.isNotEmpty(msgId)){
            ChatLogs logs = chatLogsService.getChatLogsById(msgId);
            if (logs!=null&&logs.getCreateTime()!=null){
                createTime = logs.getCreateTime();
            }
        }
        List<ChatLogs> chatLogsList = new ArrayList<>();
        if ("-1".equals(msgId)){
            return Response.makeOKRsp().setData(chatLogsList);
        }
        if(userId != null  && userId.length() > 0){ //查询单聊消息
            chatLogsList = chatLogsService.getChatLogsList(user.getUserId(),userId,createTime);
            if (chatLogsList.size()< 20){
                String kefuid = user.getKefuId();
                String recvId = userId;
                long time = user.getCreateTime().getTime();
                if(null == kefuid){
                    kefuid = user.getUserId();
                    User recvUser = userService.getUserByUserId(userId);
                    if (recvUser != null) {
                        time = recvUser.getCreateTime().getTime();
                    }
                }else {
                    recvId = user.getUserId();
                }


                List<Welcome> welcomes = welcomeService.queryWelcomeList(kefuid);
                if(!welcomes.isEmpty()){
                    User kefu = userService.getUserByUserId(kefuid);
                    int num = 1000;
                    for (Welcome welcome : welcomes){
                        ChatLogs chatLogs = new ChatLogs();
                        chatLogs.setMsgId("-1");
                        chatLogs.setSendId(kefuid);
                        chatLogs.setRecvId(recvId);
                        chatLogs.setSendTime(time+num);
                        chatLogs.setMsgType(welcome.getMsgType());
                        chatLogs.setChatType(ChatType.CHAT_TYPE_PRIVATE.getNumber());
                        chatLogs.setAvatar(kefu.getAvatar());
                        chatLogs.setNickName(kefu.getName());
                        chatLogs.setContent(welcome.getContent());
                        chatLogs.setFromType(2);
                        chatLogs.setIsRead(1);
                        chatLogs.setStatus(2);
                        chatLogs.setCreateTime(time+num);
                        num += 1000;
                        chatLogsList.add(chatLogs);
                    }
                }
            }
        }else if(groupId != null && !groupId.isEmpty()){ //查询群组消息
            chatLogsList = chatLogsService.getGroupHistoryMessage(groupId,createTime);
        }
       Collections.sort(chatLogsList, new Comparator<ChatLogs>() {
            @Override
            public int compare(ChatLogs o1, ChatLogs o2) {
                return o1.getCreateTime().compareTo(o2.getCreateTime());
            }
        });
        return Response.makeOKRsp().setData(chatLogsList);
    }


    /**
     * 撤回单聊消息
     * @param messageId 消息ID
     * @return
     */
    @RequireLogin
    @GetMapping(value ="/revokeC2C")
    public ResponseResult<Object> revokeC2C(@CurrentUser User user, String messageId){
        ChatLogs chatLogs = chatLogsService.getChatLogsById(messageId);
        if(null == chatLogs){
            return Response.makeErrRsp("没有对应消息");
        }
        chatLogs.setContent("");
        chatLogs.setMsgType(MsgType.MSG_TYPE_REVOKE.getNumber());
        if (chatLogs.getChatType() == 1){
            ImPacket imPacket = new ImPacket(Command.COMMAND_REVOKE_CHATLOGS_RESP,new RespBody(Command.COMMAND_REVOKE_CHATLOGS_RESP,chatLogs).toByte());
            JimServerAPI.sendToGroup(chatLogs.getRecvId(),imPacket);
            chatLogsService.cancelChatLog(chatLogs.getSendId(),messageId);
        }else {
            if(!chatLogs.getSendId().equals(user.getUserId())){
                return Response.makeErrRsp("异常");
            }
            ChatLogManager.sendChatLogRevokeC2C(chatLogs);
            chatLogsService.cancelChatLog(user.getUserId(),messageId);
        }

        Conversations conversationA = conversationsService.selectByUser(user.getUserId(),chatLogs.getRecvId());
        ChatBody chatBodyA = null;
        if (conversationA != null){
            chatBodyA = JsonKit.toBean(conversationA.getLastMessage(),ChatBody.class);
            if(chatBodyA != null){
                if(chatBodyA.getId().equals(messageId)){
                    chatBodyA.setMsgType(MsgType.MSG_TYPE_REVOKE.getNumber());
                    chatBodyA.setContent("");
                    conversationA.setLastMessage(JsonKit.toJSONString(chatBodyA));
                    ConversationManager.getManager().sendUserChange(conversationA);
                    conversationsService.update(conversationA);
                }
            }
        }

        return Response.makeOKRsp().setMsg("撤回成功").setData(messageId);
    }

    /**
     * 撤回群聊消息
     * @param conversationId 会话ID
     * @param messageId 消息ID
     * @param groupId 群ID
     * @return
     */
    @RequireLogin
    @GetMapping(value ="/revokeC2G")
    public ResponseResult<Object> revokeC2G(@CurrentUser User user, String conversationId,String messageId,String groupId){

        return Response.makeOKRsp("撤回成功");
    }

    /**
     * 删除消息记录
     * @param toUserId 游客Id
     * @return
     */
    @RequireLogin
    @GetMapping(value ="/deleted")
    public ResponseResult<Object> deleted(@CurrentUser User user, String toUserId){
        int result = chatLogsService.clearChatLog(user.getUserId(),toUserId);
        if(result>0){
            Response.makeOKRsp("操作成功");
        }
        return Response.makeErrRsp("操作失败");
    }

    /**
     * 消息已读
     * */
    @RequireLogin
    @GetMapping("/read")
    public ResponseResult<Object> read(@CurrentUser User user, String messageId, String fromUserId) {
        //消息已读
        ChatLogs chatLogs = new ChatLogs();
        chatLogs.setIsRead(1);
        chatLogs.setMsgId(messageId);

        ChatLogManager.sendMessageReadResp(messageId, fromUserId);

        chatLogsService.updateIsRead(fromUserId, user.getUserId());


        Conversations conversations = conversationsService.selectByUser(user.getUserId(),fromUserId);
        if(conversations != null){
            Integer count = conversations.getUnreadCount();
            if (count > 0){
                conversations.setUnreadCount(0);
                conversationsService.update(conversations);
            }
        }

        Conversations conversationB = conversationsService.selectByUser(fromUserId,user.getUserId());
        if(conversationB != null){
            ChatLogManager.sendChatLogIsRead(conversationB.getConversationId(),fromUserId);
        }
        chatLogsService.updateIsReadById(chatLogs);
        return Response.makeOKRsp("操作成功");
    }


}
